import os
import requests


_temp_flink_url = None


def get_flink_api_url() -> str:
    global _temp_flink_url
    if _temp_flink_url:
        return _temp_flink_url
    return os.environ.get("FLINK_API_URL", "http://10.1.1.26:8081")


def set_flink_api_url(url: str | None):
    global _temp_flink_url
    _temp_flink_url = url


def flink_request(method: str, endpoint: str, params=None, json=None, timeout: int = 30):
    base = get_flink_api_url().rstrip('/')
    url = f"{base}{endpoint}"
    headers = {"Content-Type": "application/json"}
    max_retries = 5
    retry_delay = 3
    last_err = None
    for retry in range(max_retries):
        try:
            resp = requests.request(method.upper(), url, params=params, json=json, headers=headers, timeout=timeout)
            if 200 <= resp.status_code < 300:
                try:
                    return True, resp.json()
                except Exception:
                    return True, resp.text
            last_err = f"HTTP {resp.status_code}: {resp.text}"
            if resp.status_code >= 500 and retry < max_retries - 1:
                import time as _t
                _t.sleep(retry_delay)
                continue
            return False, last_err
        except requests.exceptions.RequestException as e:
            last_err = str(e)
            if retry < max_retries - 1:
                import time as _t
                _t.sleep(retry_delay)
                continue
            return False, last_err
    return False, (last_err or "unknown error")


def find_latest_jar_id_by_name(jar_name_hint: str):
    ok, result = flink_request("GET", "/jars")
    if not ok or not isinstance(result, dict):
        return None, None
    files = result.get("files", []) or []
    if not files:
        return None, None
    matches = []
    if jar_name_hint:
        for f in files:
            name = f.get("name") or ""
            if jar_name_hint in name:
                matches.append(f)
    pool = matches if matches else files
    pool_sorted = sorted(pool, key=lambda x: x.get("uploaded", 0), reverse=True)
    if not pool_sorted:
        return None, None
    picked = pool_sorted[0]
    return picked.get("id"), picked.get("name")


